<template>
  <div>
    <!-- 头部 -->
    <div class="top" id="top">
      <!-- 头部bar -->
      <div class="top-bar">
        <div class="w1230 top-bar-main">
          <RouterLink to="/">
            <i class="fa fa-shopping-cart"></i>爱购网首页
          </RouterLink>
          <ul>
            <li>
              <RouterLink v-if="loginUser==null" class="login" to="/user/login">登录</RouterLink>
              <span v-if="loginUser!=null"> {{ loginUser.userName }} <a v-if="true" href=""
                                                                        @click="logout">退出</a> </span>
            </li>
            <li>
              <RouterLink v-if="loginUser==null" class="register" to="/user/register">注册</RouterLink>
            </li>
            <li v-if="loginUser!=null"><i class="fa fa-file-text-o"></i>我的订单</li>

            <li v-if="loginUser!=null">
              <router-link to="ShoppingCart">
                <i class="fa fa-shopping-cart"></i>购物车
              </router-link>
            </li>

          </ul>
        </div>
      </div>
      <!-- logo+搜索 -->
      <div class="top-header w1230 clear-float">
        <RouterLink to="/" target="_blank" class="logo">
          <img src="../assets/img/logo.png"/>
        </RouterLink>
        <div class="top-header-right">
          <!-- 搜索框 -->
          <div class="search clear-float">
            <input type="text" placeholder="牛奶" class="search-txt"/>
            <a href="#" class="search-btn">搜索</a>
          </div>
          <!-- 热搜 -->
          <p class="hotkey">
            <a href="#">牛奶</a>
            <a href="#">牛仔裤</a>
            <a href="#">巧克力</a>
            <a href="#">月饼</a>
            <a href="#">抽纸</a>
            <a href="#">狗粮</a>
            <a href="#">奶粉</a>
            <a href="#">护发素</a>
            <a href="#">进口食品</a>
            <a href="#">良品铺子</a>
          </p>
        </div>
      </div>
    </div>
    <!-- 导航栏 -->
    <div class="nav">
      <div class="w1230">
        <div id="all-goods">
          <span class="all-goods">所有商品分类</span>
          <div class="nav-er" id="nav-er">
            <ul>
              <li v-for="(productTypes, index) in productType" :key="index">
                <h3><a href="#" @click="fetchProductTypesByID(productTypes.id)"><i
                    :class="productTypes.productTypeIcon"></i>{{ productTypes.productTypeName }}</a></h3>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
    <!-- 面包屑导航栏 -->
    <div class="crumbSlide w1230">
      <i class="fa fa-th-large classify-icon"></i>
      <span>全球进口</span>
      <i class="fa fa-angle-right"></i>
    </div>

    <!--相关分类（品牌）-->
    <div class="classify-brand w1230 clear-float">
      <div class="brand-title">品牌</div>
      <div class="brands">
        <ul class="clear-float" id="brandList">
          <li v-for="(brand, index) in brands" :key="index">
            <input type="checkbox" class="chk">
            <label>
              <img :src="brand.brandImg" width="50" height="50px"><br/>{{ brand.brandName }}
              <img src="../assets/img/choose.PNG" class="choose">
            </label>
          </li>
        </ul>
      </div>
    </div>
    <!-- 综合分类 -->
    <div class="search-select w1230">
      <ul>
        <li><a href="#">综合</a></li>
        <li><a href="#">销量</a></li>
        <li><a href="#">新品</a></li>
        <li>
          <a href="javascript:void(0)">
            <span>价格</span>
            <input type="number" v-model="minPrice" placeholder="￥" min="0" class="price"/> -
            <input type="number" v-model="maxPrice" placeholder="￥" min="0" class="price"/>
          </a>
          <a href="#" class="price-sure" @click="filterByPrice">确定</a>
          <a href="#" class="price-cancel" @click="clearPrice">清空</a>
        </li>
      </ul>
    </div>
    <!--商品展示-->
    <div class="goods-show w1230">
      <ul class="clear-float" id="goodsList">
        <li v-for="(good, index) in goodsList" :key="index">
          <RouterLink :to="'/GoodsDetail/' + good.id">
            <div class="g-img"><img :src="good.productImage" alt="" width="230px" height="230px"/></div>
            <p class="g-title">{{ good.productName }}</p>
            <span class="g-price">{{ good.price }} ￥</span>
            <span class="g-num">{{ good.num }}</span>
          </RouterLink>
        </li>
      </ul>
    </div>

    <!-- 脚注 -->
    <div class="footer">
      <p class="w1230">
        <a href="#">关于爱购</a>
        <a href="#">合作伙伴</a>
        <a href="#">营销中心</a>
        <a href="#">廉正举报</a>
        <a href="#">联系客服</a>
        <a href="#">开发平台</a>
        <a href="#">诚征英才</a>
        <a href="#">联系我们</a>
        <a href="#">网站地图</a>
        <a href="#">知识产权</a><span>|</span>
        <span>&copy;2018-2020 igo.com 版权所有</span>
      </p>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import {onMounted, ref} from 'vue';

const brands = ref([]);
const loginUser = ref(null);
const filteredGoodsList = ref([])
const selectedBrands = ref([])
const goodsList = ref([])
const productType = ref([]);
const productTypeById = ref([]);

let minPrice = 0;
let maxPrice = 0;

//获取品牌
const fetchBrands = async () => {
  try {
    // 这里的 1 可替换为实际获取的当前页码
    const currentPage = 1;
    const response = await axios.get('http://127.0.0.1:8080/user/brand', {
      params: {current: currentPage}
    });
    brands.value = response.data.data.list || [];
    console.log("返回的数据：" + brands.value)
  } catch (error) {
    console.error('获取品牌列表失败', error);
  }
};
//获取商品列表
const fetchProducts = async () => {
  try {
    // 这里的 1 可替换为实际获取的当前页码
    const currentPage = 1;
    const response = await axios.get('http://127.0.0.1:8080/user/product', {
      params: {current: currentPage}
    });
    goodsList.value = response.data.data.list || [];
    console.log("商品数据：" + goodsList.value)
  } catch (error) {
    console.error('获取品牌列表失败', error);
  }
};
//获取商品类型
const fetchProductTypes = async () => {
  try {
    // 从第 1 页开始查询
    const currentPage = 1;
    const response = await axios.get('http://127.0.0.1:8080/user/ProductType', {
      params: {current: currentPage}
    });
    productType.value = response.data.data.list || [];
    console.log("商品类型数据：" + productType.value)
  } catch (error) {
    console.error('获取商品分类数据失败', error);
  }
};
//根据商品类型ID查询商品
const fetchProductTypesByID = async (id) => {
  try {
    const response = await axios.get('http://127.0.0.1:8080/user/product/selectProductTypeID', {
      params: {productTypeID: id}
    });
    goodsList.value = response.data.data || [];
    console.log("根据商品类型ID查询商品：" + productTypeById.value)
  } catch (error) {
    console.error('获取商品分类数据失败', error);
  }
};
//退出登录
const logout = () => {
  loginUser.value = null;
  localStorage.removeItem("user");
  this.$router.push("/");
}
const clearPrice = () => {
  minPrice = 0;
  maxPrice = 0;
}
const filterByPrice = () => {
  console.log("价格筛选")
  filteredGoodsList.value = goodsList.value.filter(item => {
    return item.price >= minPrice && item.price <= maxPrice;
  });
  goodsList.value = filteredGoodsList.value
  console.log(filteredGoodsList.value)
}
const goToDetail = (href) => {
  r
  this.$router.push(href);
}
const handleBrandSure = () => {
  this.selectedBrands = [];
  const checkedBoxes = document.querySelectorAll('.chk:checked');
  checkedBoxes.forEach((box) => {
    const label = box.nextElementSibling;
    const brandName = label.textContent.trim().split('\n')[1];
    this.selectedBrands.push(brandName);
  });
  // 根据selectedBrands对商品列表进行筛选
  console.log('已选择的品牌:', this.selectedBrands);
}
const handleBrandCancel = () => {
  const allCheckboxes = document.querySelectorAll('.chk');
  allCheckboxes.forEach((box) => {
    box.checked = false;
  });
  this.selectedBrands = [];
}
onMounted(() => {
  fetchBrands();
  fetchProducts();
  fetchProductTypes();
  fetchProductTypesByID();
  const user = localStorage.getItem("user");
  if (user) {
    try {
      loginUser.value = JSON.parse(user);
    } catch (error) {
      console.error('解析用户数据出错', error);
    }
  }
})


</script>


<style scoped>
@import '../assets/css/reset.css';
@import "../assets/css/top.css";
@import "../assets/css/index.css";
@import "../assets/css/footer.css";
@import "../assets/css/font-awesome-4.7.0/Font-Awesome-master/css/font-awesome.min.css";
@import '../assets/css/buyerTrade.css';
@import '../assets/css/classify.css';
@import '../assets/css/deliverAddress.css';
@import '../assets/css/goodsDetail.css';
@import '../assets/css/login.css';
@import '../assets/css/shoppingCart.css';

</style>